package getui

import (
	"bytes"
	"crypto/sha256"
	"data/config"
	"encoding/hex"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"public/mycache"
	"public/myhttp"
	"public/mylog"
	"strconv"
	"time"
)

var appId string
var appKey string
var masterSecret string

func init() {
	getui_info := config.GetGeTuiInfo()
	//配置个推参数
	appId = getui_info.AppID
	appKey = getui_info.AppKey
	masterSecret = getui_info.MasterSecret
}

//鉴权
func AuthSign() (token string) {
	//先从缓存中获取
	cache := mycache.OnGetCache("getui_token")
	var tp interface{}
	tp, b := cache.Value("base")
	if b {
		token = tp.(string)
	} else {
		timestamp := strconv.FormatInt(time.Now().UnixNano()/1e6, 10) //10进制

		var url = "https://restapi.getui.com/v1/" + appId + "/auth_sign"
		var req AuthReq
		var result AuthResponse

		h := sha256.New()
		h.Write([]byte(appKey + timestamp + masterSecret))
		bs := h.Sum(nil)

		req.Sign = hex.EncodeToString(bs) //sha256(appkey+timestamp+mastersecret)
		req.Timestamp = timestamp
		req.Appkey = appKey

		myhttp.SendPost(req, &result, url)

		token = result.Auth_token
		//保存缓存
		cache.Add("base", token, 23*time.Hour)
	}

	return
}

/*
	单推
	cid和alias二选其一
	requestid: 请求唯一标识 length should be 10~30
	transmission_type:收到消息是否立即启动应用，true为立即启动，false则广播等待启动，默认是否
	transmission_content:透传内容
*/
func SendSingleMsg(cid, alias, requestid, transmission_content, text, title string, transmission_type bool) (result MsgResponse) {
	var url = "https://restapi.getui.com/v1/" + appId + "/push_single"
	var req SingleReq
	req.Message.Appkey = appKey
	req.Message.Is_offline = false
	req.Message.Msgtype = "notification"
	if len(cid) > 0 {
		req.Cid = cid
	}
	if len(req.Alias) > 0 {
		req.Alias = alias
	}
	req.Requestid = requestid
	req.Notification.Transmission_type = transmission_type
	req.Notification.Transmission_content = transmission_content
	req.Notification.Style.Text = text   //通知内容
	req.Notification.Style.Title = title //通知标题
	req.Notification.Style.Is_clearable = true
	req.Notification.Style.Is_ring = true
	req.Notification.Style.Is_vibrate = true
	SendPostWithToken(req, &result, AuthSign(), url)
	return
}

//发送POST请求
func SendPostWithToken(requestBody interface{}, responseBody interface{}, authtoken, url string) bool {
	postData, err := json.Marshal(requestBody)
	client := &http.Client{}
	req, _ := http.NewRequest("POST", url, bytes.NewReader(postData))
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Content-Type", "application/json;charset=utf-8")

	// 大小写有特殊要求的用下面这种方式添加
	req.Header["authtoken"] = []string{authtoken}

	resp, e := client.Do(req)
	if e != nil {
		mylog.Error(e)
		return false
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		mylog.Error(e)
		return false
	}
	//	result := string(body)
	mylog.Debug(string(body))

	err = json.Unmarshal(body, &responseBody)
	return err == nil
}
